package com.ctg.behavior.client.impala.factory;

import java.sql.Connection;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ctg.behavior.client.impala.config.CtImpalaAbandonedConfig;
import com.ctg.behavior.client.impala.config.CtImpalaConfig;
import com.ctg.behavior.client.impala.config.CtImpalaPoolConfig;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtImpalaPool {

	/**
	 * CtImpala Connection 客户端连接池
	 */
	private GenericObjectPool<Connection> impalaPool;
	/**
	 * CtImpala Connection 客户端工厂
	 */
	@Autowired
	private CtImpalaFactory impalaFactory;
	@Autowired
	private CtImpalaPoolConfig ctImpalaPoolConfig;
	@Autowired
	private CtImpalaConfig ctImpalaConfig;
	@Autowired
	private CtImpalaAbandonedConfig abandonedConfig;

	/**
	 * 初始化MaxIdle个链接
	 * 
	 * @return
	 * @throws Exception
	 */
	public boolean initPool() throws Exception {
		if (!ctImpalaConfig.getLanuch()) {
			log.warn("CTIMPALA NOT LANUCH.");
			return false;
		}
		// 创建连接信息(可多个连接)
		impalaPool = new GenericObjectPool<Connection>(impalaFactory, ctImpalaPoolConfig, abandonedConfig);
		for (int index = 0; index < ctImpalaPoolConfig.getMaxIdle(); index++) {
			impalaPool.addObject();
		}
		return true;
	}

	/**
	 * 获取一个连接对象
	 * 
	 * @return
	 * @throws Exception
	 */
	public Connection openConnection() {
		try {
			return impalaPool.borrowObject();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 归还一个连接对象
	 * 
	 * @param hbaseConnection
	 */
	public void closeConnection(Connection hbaseConnection) {
		if (hbaseConnection != null) {
			impalaPool.returnObject(hbaseConnection);
		}
	}

}